﻿using System;
using System.IO;
using System.Windows.Forms;

namespace FileMergeApp
{
    public partial class FileMergeForm : Form
    {
        public FileMergeForm()
        {
            InitializeComponent();
        }

        private void btnSelectFile1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                Title = "选择第一个文件"
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFile1.Text = openFileDialog.FileName;
            }
        }

        private void btnSelectFile2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                Title = "选择第二个文件"
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFile2.Text = openFileDialog.FileName;
            }
        }

        private void btnMergeFiles_Click(object sender, EventArgs e)
        {
            string file1Path = txtFile1.Text;
            string file2Path = txtFile2.Text;

            if (string.IsNullOrEmpty(file1Path) || string.IsNullOrEmpty(file2Path))
            {
                MessageBox.Show("请先选择两个文件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!File.Exists(file1Path) || !File.Exists(file2Path))
            {
                MessageBox.Show("其中一个文件不存在，请重新选择。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 获取可执行程序路径，并确保 Data 文件夹存在
                string exeDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string dataDirectory = Path.Combine(exeDirectory, "Data");
                if (!Directory.Exists(dataDirectory))
                {
                    Directory.CreateDirectory(dataDirectory);
                }

                // 合并的文件路径
                string mergedFilePath = Path.Combine(dataDirectory, "MergedFile.txt");

                // 读取两个文件的内容并写入到新文件
                using (StreamWriter writer = new StreamWriter(mergedFilePath))
                {
                    writer.WriteLine(File.ReadAllText(file1Path));
                    writer.WriteLine(File.ReadAllText(file2Path));
                }

                MessageBox.Show($"文件合并成功！文件存储路径：\n{mergedFilePath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"文件合并时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
